from flask import g, redirect, render_template, request, jsonify, current_app, abort

from info import db, constants
from info.models import Category, News, User
from info.modules.profile import profile_blu
from info.utils.common import user_login_data
from info.utils.image_storage import storage
from info.utils.response_code import RET


@profile_blu.route("/info")
@user_login_data
def user_info():
    if not g.user:
        return redirect("/")
    data = {"user": g.user.to_dict()}
    return render_template('news/user.html', data=data)


@profile_blu.route('/base_info', methods=["GET", "POST"])
@user_login_data
def base_info():
    if request.method == "GET":
        data = {
            "user": g.user.to_dict()
        }
        return render_template("news/user_base_info.html", data=data)
    # 不是GET请求代表用户进行数据修改
    # 1 获取用户传入的数据
    nick_name = request.json.get("nick_name")
    signature = request.json.get("signature")
    gender = request.json.get("gender")
    # 2校验参数
    if not all([nick_name, signature, gender]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    if gender not in ["WOMAN", "MAN"]:
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    g.user.nick_name = nick_name
    g.user.signature = signature
    g.user.gender = gender
    db.session.commit()
    return jsonify(errno=RET.OK, errmsg="OK")


@profile_blu.route('/pic_info', methods=["GET", "POST"])
@user_login_data
def pic_info():
    if request.method == "GET":
        data = {
            "user": g.user.to_dict()
        }
        return render_template("news/user_pic_info.html", data=data)
    # 如果是post请求，则修改头像
    # 1 获取上传的头像
    try:
        avatar = request.files.get("avatar").read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    # 2 上传头像
    try:
        # 使用自已封装的storage方法去进行图片上传
        key = storage(avatar)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg="上传头像失败")
    # 3保存头像地址
    g.user.avatar_url = key
    db.session.commit()
    data = {
        "avatar_url": constants.QINIU_DOMIN_PREFIX + key
    }
    return jsonify(errno=RET.OK, errmsg="OK", data=data)


@profile_blu.route('/pass_info', methods=["GET", "POST"])
@user_login_data
def pass_info():
    if request.method == "GET":
        return render_template('news/user_pass_info.html')
    # 1 获取参数
    old_password = request.json.get("old_password")
    news_password = request.json.get("news_password")
    # 2. 校验参数
    if not all([old_password, news_password]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    # 3判断旧密码是否正确
    if not g.user.check_password(old_password):
        return jsonify(errno=RET.PWDERR, errmsg="原始密码错误")
    # 4设置新密码
    g.user.password = news_password
    db.session.commit()
    return jsonify(errno=RET.OK, errmsg="保存成功")


@profile_blu.route('/collection')
@user_login_data
def user_collection():
    # 1获取元素
    page = request.args.get("p", 1)
    # 2判断参数
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1
    # 3查询用户指定页数的收藏的新闻
    total_page = 1
    current_page = 1
    news_list = []
    try:
        paginate = g.user.collection_news.paginate(page, constants.USER_COLLECTION_MAX_NEWS, False)
        current_page = paginate.page
        total_page = paginate.pages
        news_list = paginate.items
    except Exception as e:
        current_app.logger.error(e)
    news_dict_li = []
    for news in news_list:
        news_dict_li.append(news.to_basic_dict())
    data = {
        "total_page": total_page,
        "current_page": current_page,
        "collections": news_dict_li
    }
    return render_template("news/user_collection.html", data=data)


@profile_blu.route("/news_release", methods=["get", "post"])
@user_login_data
def news_release():
    if request.method == "GET":
        # 加载新闻分类页面
        categories = []
        try:
            categories = Category.query.all()
        except Exception as e:
            current_app.logger.error(e)

        category_dict_li = []
        for category in categories:
            category_dict_li.append(category.to_dict())
        # 移除最新类
        category_dict_li.pop(0)
        data = {
            "categories": category_dict_li
        }
        return render_template("news/user_news_release.html", data=data)
    # 1获取需要提交的数据
    # 标题
    title = request.form.get("title")
    # 新闻来源
    source = "个人发布"
    # 摘要
    digest = request.form.get("digest")
    # 新闻内容
    content = request.form.get("content")
    # 索引图片
    index_image = request.files.get("index_image")
    # 分类id
    category_id = request.form.get("category_id")
    # 校验参数
    # 2 判断数据是否有值
    if not all([title, source, digest, content, index_image, category_id]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")
    try:
        category_id = int(category_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")
    # 取到图片，将图片上传至七牛云
    try:
        index_image_data = index_image.read()
        key = storage(index_image_data)
    except  Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")
    news = News()
    news.title = title
    news.digest = digest
    news.source = source
    news.content = content
    news.index_image_url = constants.QINIU_DOMIN_PREFIX + key
    news.category_id = category_id
    news.user_id = g.user.id
    # 1代表待审核状态
    news.status = 1
    try:
        db.session.add(news)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据保存失败")
    return jsonify(errno=RET.OK, errmsg="发布成功，等待审核")


@profile_blu.route('/news_list')
@user_login_data
def user_news_list():
    # 获取参数
    page = request.args.get("p", 1)
    # 判断参数
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1
    user = g.user
    news_list = []
    current_page = 1
    total_page = 1
    try:
        paginate = News.query.filter(News.user_id == user.id).paginate(page, constants.USER_COLLECTION_MAX_NEWS, False)
        news_list = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    news_dict_li = []

    for news in news_list:
        news_dict_li.append(news.to_review_dict())

    data = {
        "news_list": news_dict_li,
        "total_page": total_page,
        "current_page": current_page,
    }
    return render_template('news/user_news_list.html', data=data)


@profile_blu.route('/user_follow', methods=["get", "post"])
@user_login_data
def user_follow():
    if request.method == "GET":
        # 获取页面
        page = request.args.get("p", 1)
        try:
            page = int(page)
        except Exception as e:
            current_app.logger.error(e)
            page = 1
        user = g.user
        follows = []
        current_page = 1
        total_page = 1
        # 数据查询
        try:
            paginate = user.followed.paginate(page, constants.USER_FOLLOWED_MAX_COUNT, False)
            follows = paginate.items
            current_page = paginate.page
            total_page = paginate.pages
        except Exception as e:
            current_app.logger.error(e)
        user_dict_li = []
        for follow in follows:
            user_dict_li.append(follow.to_dict())
        data = {
            "users": user_dict_li,
            "total_page": total_page,
            "current_page": current_page
        }
        return render_template('news/user_follow.html', data=data)
    # 获取提交的参数
    # UUTD 取消关注功能待完善


@profile_blu.route('/other_info')
@user_login_data
def other_info():
    # 查看其他用户信息
    # 1获取当前登录用户
    user = g.user
    # 2获取其他用户ID
    user_id = request.args.get("user_id")
    if not user_id:
        abort(404)
    # 3查询用户模型
    other = None
    try:
        other = User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)
    if not other:
        abort(404)
    # 4判断当前用户是否关注过该用户
    is_followed = False
    if user:
        if other.followers.filter(User.id == user.id).count() > 0:
            is_followed = True

    data = {"user": user.to_dict() if user else None,
            "other_info": other.to_dict(),
            "is_followed": is_followed}
    return render_template('news/other.html', data=data)


@profile_blu.route('/other_news_list')
@user_login_data
def other_news_list():
    """返回指定用户的发布的新闻"""
    # 1 获取参数
    page = request.args.get("p", 1)
    other_id = request.args.get("user_id")
    # 2. 判断参数
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    other = None
    try:
        other = User.query.get(other_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询失败")
    if not other:
        return jsonify(errno=RET.NODATA, errmsg="当前用户不存在")
    try:
        paginate = other.news_list.paginate(page, constants.USER_COLLECTION_MAX_NEWS, False)
        news_li = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询失败")
    news_dict_li = []
    for news in news_li:
        news_dict_li.append(news.to_basic_dict())
    data = {
        "news_list": news_dict_li,
        "total_page": total_page,
        "current_page": current_page
    }
    return jsonify(errno=RET.OK, errmsg="OK", data=data)
